package com.zdxlz.fcmp.common.core.exception;

import com.zdxlz.fcmp.common.core.constant.enums.ResCode;
import com.zdxlz.fcmp.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @className GlobalExceptionHandler
 * @description 全局异常处理器
 * @author: aman
 * @date 2025/1/30 17:21
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BizException.class)
    public <T> R<T> handleBizException(BizException e) {
        log.error("捕获业务异常，业务异常状态码：{}，业务异常消息：{}", e.errorCode, e.getMessage());
        return R.failed(e.getErrorCode(), e.getMessage());
    }

    @ExceptionHandler(value = DataIntegrityViolationException.class)
    public <T> R<T> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
        log.error("捕获数据库【unique】重复异常", e);
        return R.failed(ResCode.DATABASE_UNIQUE_REPEAT.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public <T> R<T> handleRuntimeException(RuntimeException e) {
        log.error("捕获运行时异常", e);
        return R.failed(ResCode.ERR_COMMON_UN_KNOW.getCode(), ResCode.ERR_COMMON_UN_KNOW.getReason());
    }

    @ExceptionHandler(value = NullPointerException.class)
    public <T> R<T> handleNullPointerException(NullPointerException e) {
        log.error("捕获空指针异常", e);
        return R.failed(ResCode.ERR_COMMON_UN_KNOW.getCode(), ResCode.ERR_COMMON_UN_KNOW.getReason());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public <T> R<T> handleException(MethodArgumentNotValidException e) {
        log.error("捕获参数校验异常，异常信息：{}", e.getBindingResult().getFieldError().getDefaultMessage(), e);
        return R.failed(ResCode.ERR_COMMON_LACK.getCode(), e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public <T> R<T> handleException(Exception e) {
        log.error("捕获系统异常", e);
        return R.failed(ResCode.ERR_COMMON_UN_KNOW.getCode(), ResCode.ERR_COMMON_UN_KNOW.getReason());
    }
}
